package com.eascs.admin.o2o.loanAccount.serviceimpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.eascs.account.api.IFeeService;
import com.eascs.account.api.constants.enums.SourceType;
import com.eascs.account.api.constants.enums.TradeType;
import com.eascs.account.api.vo.TradeDetailVO;
import com.eascs.account.api.vo.TradeParamsVO;
import com.eascs.admin.common.utils.AccountConstants;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loanAccount.dao.O2oCollectFeesDao;
import com.eascs.admin.o2o.loanAccount.entity.AccountLog;
import com.eascs.admin.o2o.loanAccount.entity.O2oCollectFee;
import com.eascs.admin.o2o.loanAccount.service.IAccountLogService;
import com.eascs.admin.o2o.loanAccount.service.IO2oCollectFeesService;
import com.eascs.admin.o2o.loanAccount.vo.O2oCollectFeesVo;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UuidUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service
public class O2oCollectFeesService implements IO2oCollectFeesService {
	private final Logger logger = LoggerFactory.getLogger(O2oCollectFeesService.class);
	@Autowired
	O2oCollectFeesDao o2oCollectFeesDao;
	@Reference
	private CustomerService customerService;
	@Reference
	private IFeeService feeService;

	@Autowired
	private IAccountLogService accountLogService;

	@Value("${o2o.admin.wf.collectFeesUrl}")
	private String collectFeesUrl;

	@Reference
	private WorkFlowService workFlowService;

	@Override
	public PageResult<Object[]> queryByPageCollectFee(O2oCollectFeesVo vo) {

		return o2oCollectFeesDao.queryByPageCollectFee(vo);
	}
	
	public PageResult<Object[]> queryByPageCollectFeeExport(O2oCollectFeesVo vo) {
		
		return o2oCollectFeesDao.queryByPageCollectFeeExport(vo);
	}

	@Override
	public O2oCollectFee queryById(String id) {

		return o2oCollectFeesDao.getById(O2oCollectFee.class, id);
	}

	public O2oCollectFee queryByBillCode(String billCode) {
		String sql = "select * from o2o_collect_fees where bill_code=?";
		return o2oCollectFeesDao.findEntity(sql, O2oCollectFee.class, billCode);
	}

	@Override
	public int save(O2oCollectFee entity) {

		return o2oCollectFeesDao.insert(entity);
	}

	@Override
	public int update(O2oCollectFee entity) {

		return o2oCollectFeesDao.updateById(entity);
	}

	/**
	 * @Title: personal_collectFees
	 * @Description: 个人打款
	 * @author 张庆奇
	 * @param entity
	 * @param type
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年12月7日 下午2:18:42
	 */
	@Override
	public String personal_collectFees(O2oCollectFee entity, String type) {
		AccountLog accountLog = new AccountLog();
		accountLog.setStartTime(new Date());
		accountLog.setId(UuidUtil.generateShortUuid());
		logger.info("调用个人账户开户查询接口参数：【{}】", JSONObject.toJSONString(entity.getLoanId()));
		CustomerEntity customerEntity = customerService.queryCustomerEntityByCustomerId(entity.getLoanId());
		logger.info("调用个人账户开户查询接口结果：【{}】", JSONObject.toJSONString(customerEntity));
		if (null == customerEntity) {
			return "借款人个人账户未开户，请联系运维同事";
		}

		TradeDetailVO tradeDetailVO = new TradeDetailVO();// 封装交易明细数据

		TradeParamsVO paramsVO = new TradeParamsVO();

		tradeDetailVO.setAmount(entity.getCollectMoney());
		tradeDetailVO.setRollInAccount(customerEntity.getAccountId());
		// tradeDetailVO.setTradeBankcardNoIn("");// 本方交易银行卡号
		tradeDetailVO.setTradeBankcardNoOut(entity.getCollectNo());// 对方交易银行卡号
		tradeDetailVO.setTradeDate(new Date());
		tradeDetailVO.setTradeType(TradeType.RECHARGE);
		String remark="客户名："+entity.getLoanName()+";流程编号："+entity.getBillCode();
		tradeDetailVO.setRemark(remark);
		List<TradeDetailVO> detailsVO = new ArrayList<TradeDetailVO>();
		detailsVO.add(tradeDetailVO);
		paramsVO.setBizId(entity.getId());
		paramsVO.setBizType(AccountConstants.ACCOUNT_SF);
		paramsVO.setDetails(detailsVO);
		paramsVO.setRequestId(accountLog.getId());
		paramsVO.setUniqueId(UuidUtil.generateShortUuid());
		paramsVO.setSource(SourceType.WEB);
		paramsVO.setRemark(remark);
		ModelResult<String> result = null;
		try {
			logger.info("调用个人账户打款接口开始，参数：【{}】", JSONObject.toJSONString(paramsVO));
			result = feeService.fee(paramsVO);
			logger.info("调用个人账户打款接口结束，成功与否：{},【信息：{}】", result.isSuccess(), result.getErrMsg());
			if (result.isSuccess()) {// 如果调用成功

				logger.info("更新借款对象account_id信息开始");
				entity.setAccountId(result.getModel());
				update(entity);
				logger.info("更新借款对象account_id信息结束");
				return "SUCCESS";
			} else {
				return result.getErrMsg();
			}
		} catch (Exception e) {
			logger.error("调用个人账户打款接口失败，失败信息为：{}", e.getMessage());
			return "个人账户打款失败";
		} finally {
			if (result.isSuccess()) {
				accountLog.setStatus(String.valueOf(result.isSuccess()));
			} else {
				accountLog.setStatus("false");
			}
			accountLog.setEndTime(new Date());
			accountLog.setRequestid(entity.getId());
			accountLog.setRequestPs(JSONObject.toJSONString(paramsVO));
			accountLog.setResponsePs(JSONObject.toJSONString(result));
			accountLog.setClassname(this.getClass().getName());
			accountLog.setLogType(AccountConstants.ACCOUNT_SF);
			accountLog.setLoanapplyNo(entity.getId());
			accountLog.setMethodname(Thread.currentThread().getStackTrace()[1].getMethodName());
			logger.info("调用service账号接口开始");
			accountLogService.add(accountLog);
			logger.info("调用service账号接口结束");
		}
	}

	@Override
	public com.eascs.admin.common.vo.ModelResult<Boolean> startup(O2oCollectFee entity, String operatorNo, String operatorName) {
		com.eascs.admin.common.vo.ModelResult<Boolean> result = new com.eascs.admin.common.vo.ModelResult<Boolean>();
		logger.info("个人账户收费对象：{}", entity);
		WFRequestParam param = new WFRequestParam();
		param.setReferId(entity.getId());
		param.setReferCode(entity.getBillCode());
		param.setReferUrl(collectFeesUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("ACCOUNT_REMITTANCE");
		param.setProcessVersion("v1");
		User user = null;
		if (null == UserHolder.getUser() && StringUtil.isNotBlank(operatorNo)) {
			user = new User();
			user.setNo(operatorNo);
			user.setCname(operatorName);
		} else {
			user = UserHolder.getUser();
		}
		param.setAppliedby(entity.getCreateId());
		param.setAppliedbyName(entity.getCreateName());
		param.setOrgNo(entity.getLtd());
		// param.setReferUrl(backfeeUrl + "?billCode=" +
		// o2oZxEntity.getId()+"&type=1");
		StringBuffer appliedDes = new StringBuffer("姓名:");
		appliedDes.append(entity.getLoanName());
		appliedDes.append("，打款金额:" + entity.getCollectMoney());
		appliedDes.append("，打款时间:" + entity.getBreakDate());
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交个人账户打款，参数有id：【{}】，编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", entity.getId(), entity.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), entity.getLtd(), appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			entity.setStatus(StatusContexts.WFTYPE_STATUS_RUN);
			entity.setSubmitId(user.getNo());
			entity.setSubmitName(user.getCname());
			entity.setSubmitDate(new Date());
			update(entity);
			result.withModel(modelResult.getModel());
		} else {
			logger.error("提交个人账户打款流程失败，错误信息:【{}】", modelResult.getErrMsg());
			result.withError(modelResult.getErrCode(), modelResult.getErrMsg());
		}
		return result;
	}

	@Override
	public com.eascs.admin.common.vo.ModelResult<Boolean> queryListCollectFee() {
		logger.info("定时器启动打款流程调用接口");
		com.eascs.admin.common.vo.ModelResult<Boolean> result = new com.eascs.admin.common.vo.ModelResult<Boolean>();
		try {
			String sql = "select oblt.collect_fees_id,ol.operator_no,ol.operator_name from o2o_bank_loan_data_timer oblt LEFT JOIN o2o_loanapply ol on oblt.loanapply_no=ol.loanapply_no where oblt.flow_status='N' and oblt.is_stup='N' and oblt.collect_fees_id is not null";
			List<Object[]> collectIds = o2oCollectFeesDao.findEntitys(sql, Object[].class);
			if (null != collectIds && collectIds.size() > 0) {
				int i = 0;
				String rsg = "";
				for (Object id[] : collectIds) {
					i++;
					O2oCollectFee entity = queryById(id[0].toString());
					if (StatusContexts.BZJ_STATUS_NEW.endsWith(entity.getStatus())) {
						result = startup(entity, id[1].toString(), id[2].toString());
						if (result.isSuccess()) {
							String updateSql = "update o2o_bank_loan_data_timer set is_stup='Y' where collect_fees_id=?";
							o2oCollectFeesDao.execute(updateSql, entity.getId());
						}
						rsg += "第" + i + "条： " + result.getErrMsg() + "";
					}
				}
				logger.info("启动个人打款流程信息：【{}】", rsg);
				return result;
			}
		} catch (Exception e) {
			logger.error("定时器启动打款流程异常，信息：【{}】", e.getMessage());
			result.withError("ERROR", "定时器启动打款流程异常，信息：【" + e.getMessage() + "】");
			return result;
		}
		result.withError("FALSE", "导入放款信息为空，无法放款");
		return result;
	}

}
